//
//  SLOAuthController.swift
//  Sina15
//
//  Created by 盼 on 16/4/9.
//  Copyright © 2016年 pan. All rights reserved.
//

import UIKit
import SVProgressHUD

class SLOAuthController: UIViewController {
    
    let webView = UIWebView()
    
    override func loadView() {
        
        view = webView
        
        //给webView设置代理
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
//        https://api.weibo.com/oauth2/authorize?client_id=123050457758183&redirect_uri=http://www.example.com/response&response_type=code
    
        //设置导航栏的item
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "fullfil")
        
//        使用webView加载授权页面
//        let URLStr = "https://api.weibo.com/oauth2/authorize?client_id=360894052&redirect_uri=http://git.oschina.net/thus"
        
        let URLStr = "https://api.weibo.com/oauth2/authorize?client_id="+client_id+"&redirect_uri="+redirect_uri
        
        let url = NSURL(string: URLStr)
        
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
        
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        //隐藏HUD
        SVProgressHUD.dismiss()
    }
    
    //关闭按钮的点击事件
  @objc private func close() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    @objc private func fullfil() {
        
        //        document.getElementById('userId').value = '1152934913@qq.com'
//        document.getElementById('passwd').value = '199109248168pp'
        
        //使用JS代码一键设置用户名
    webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '1152934913@qq.com',document.getElementById('passwd').value = '199109248168pp'")
    }

}



extension SLOAuthController: UIWebViewDelegate {
    
    //开始加载页面的时候显示等待指示器
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    //页面加载完成以后移除等待指示器
    func webViewDidFinishLoad(webView: UIWebView) {
        
        //执行js代码获取文档的title
        let webTitle = webView.stringByEvaluatingJavaScriptFromString("document.title")
        
        title = webTitle
        
        SVProgressHUD.dismiss()
    }
    
    //加载网络请求的
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
        
        let URLStr = request.URL?.absoluteString ?? ""
        
        let str = "code="
        
        if URLStr.containsString(str) {
            
            let range = URLStr.rangeOfString(str)
            
            let code = URLStr.substringFromIndex((range?.endIndex)!)
            
            
            //获取accessToken
//            SLUserViewModel.sharedModel.loadAccessToken(code,finished: (isSuccess: Bool)->())
            SLUserViewModel.sharedModel.loadAccessToken(code, finished: { (isSuccess) -> () in
                
                if !isSuccess {
                    SVProgressHUD.showErrorWithStatus("授权不成功")
                    
                    return
                }
                
                //授权成功后要登录，跳转到欢迎页面，需要用户的账户信息
                SVProgressHUD.showSuccessWithStatus("授权成功")
                
        //因为OAuth控制器是modal出来的控制器，从欢迎界面跳转到首页的时候，必须先把OAuth控制器dismiss掉，否则会驻留在视图层次结构中

            //动画显示完成之后，dismiss modal出来的控制器
                self.dismissViewControllerAnimated(true, completion: { () -> Void in

                    //发送通知通知app修改根控制器
                    NSNotificationCenter.defaultCenter().postNotificationName(switchRootViewController, object: nil)
                })
                

            })
            
            return false
        }
        
        return true
    }
    
    
}
